package cn.org.timespace.ons.util.datatime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class DateMonthUtil {
	
	private static final int DEF_START_YEAR = 2010;
	
	/**
	 *计算两个月之间的月份，前提条件是startMonth永远比endMonth小。
	 *格式为：yyyyMM,yyyyMM,... 
	 */
	public static String getMonthListBetween2Month(String startMonth,String endMonth){
		String strMonth = "";
		String edMonth = "";
		
		String defStrMonth = "201009";   //默认的开始月
		String defEndMonth = "201009";   //默认的结束月
		
		//获取默认的开始月
		Calendar cal = Calendar.getInstance();
		if(cal.get(Calendar.YEAR) == DEF_START_YEAR) {defStrMonth = "201009"; }
		else { defStrMonth = cal.get(Calendar.YEAR)+"01"; }
		
		//获取默认的结束月
		defEndMonth = new SimpleDateFormat("yyyyMM").format(new Date());
		
		
		if(StringUtils.isEmpty(startMonth) && StringUtils.isEmpty(endMonth)){
			strMonth = defStrMonth;
			edMonth = defEndMonth;
			
		}else if(!StringUtils.isEmpty(startMonth) && !StringUtils.isEmpty(endMonth)){
			strMonth = startMonth;
			edMonth = endMonth;
			
		}
		
		//计算两个月份之间的月份
		int firstYear = Integer.parseInt(strMonth.substring(0,4));
		int secondYear = Integer.parseInt(edMonth.substring(0,4));
		int firstMonth = Integer.parseInt(strMonth.substring(4,6));
		int secondMonth = Integer.parseInt(edMonth.substring(4,6));
		
		int monthSub = (secondYear - firstYear) * 12 + (secondMonth - firstMonth);
		
		StringBuffer months = new StringBuffer();
		Calendar calc = Calendar.getInstance();
		calc.set(firstYear, firstMonth-1, 1);
		for(int m=0;m<=monthSub;m++){
			months.append(calc.get(Calendar.YEAR)).append(fullMonth(calc.get(Calendar.MONTH)+1)).append(",");
			calc.add(Calendar.MONTH, 1);
		}
		
		return months.toString().substring(0,months.toString().length()-1);
	}
	
	public static String fullMonth(int m){
		if(String.valueOf(m).length() == 1) return "0"+m;
		else return ""+m;
	}
	
	/**
	 * 将字符串组成的月份转换成List
	 * @param s
	 * @return
	 */
	public static List<String> stringToList(String s){
		List<String> res = new ArrayList<String>();
		
		String[] mArr = s.split(",");
		for(int i=0;i<mArr.length;i++){
			res.add(mArr[i]);
		}
		
		return res;
	}
	
	public static String getCutYearMonth(){
		return new SimpleDateFormat("yyyy-MM").format(new Date());
	}

	public static void main(String[] args) {
		String s = DateMonthUtil.getMonthListBetween2Month("","");
		System.out.println(s);
		System.out.println(DateMonthUtil.stringToList(s));
		
		s = DateMonthUtil.getMonthListBetween2Month("201010","201103");
		System.out.println(s);
		System.out.println(DateMonthUtil.stringToList(s));
	}

}
